import logging
import os
import traceback

import requests
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

from api_test.common.api_response import JsonResponse
from api_server.utils import *

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。

game_message_info = {"request": {"townest":"GatewayPackageRequest"}, "response": {"townest":"GatewayPackageResponse"}}
proto_file_name = get_proto_filename(os.path.dirname(os.path.abspath(__file__)), game_message_info)


class TownestGame(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['url', 'body'],
        properties={
            'url': openapi.Schema(type=openapi.TYPE_STRING, description="url地址 eg.http://xxx.com/account"),
            'body': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数"),
            'login': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数，body参数依赖的登录请求参数"),
        },
    ))
    def post(self, request):
        """
        townest http+protobuf
        """
        # {"url":"http://qausa.gameyici.com"}
        # {"body": {"senderId": "1", "sessionId": 2, "bodys": [{"code":1, "msgId":1001, "msgBody":{}, "genTime":time.time(), "vdersion":"1.5"}]}}
        # {"type": 0, "account": "1PtHcn6V", "osType": 2, "platformType": 0}
        # TODO bodys可发多个消息，目前只支持解析一个消息
        try:
            data = JSONParser().parse(request)

            bodys_msgId = data["body"]["bodys"][0]["msgId"]

            # 先根据body[msgId]序列化body[msgBody], 最后再序列化整个body
            raw_bodys_data = pb2seria(game_message_info["request"], data["body"]["bodys"][0])

            data["body"]["bodys"][0]["msgBody"] = raw_bodys_data
            raw_data = pb2seria(game_message_info["request"], data["body"])

            url = data["url"]
            result = requests.put(url, data=raw_data)
            # print("status code:" + str(result.status_code))

            message = eval(game_message_info["response"]["townest"])()
            # 先反序列化整个body，再反序列化bodys[msgBody]
            message.ParseFromString(result.content)
            json_dict = pb2dict(message)

            code_body = json_dict["bodys"][0]["msgId"]
            message_body = eval(game_message_info["response"][str(code_body)])()
            message_body.ParseFromString(json_dict["bodys"][0]["msgBody"])
            json_dict_body = pb2dict(message_body)
            json_dict["bodys"][0]["msgBody"] = json_dict_body

            return JsonResponse(data={
                "data": json_dict, "status": str(result.status_code) + " " + str(result.reason)
            }, code="999999", msg="成功")
        except Exception as e:
            return JsonResponse(code="999990", msg="失败", data={"error": str(e)})

